package com.liliudong.mybatissql

import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.ui.Messages
import java.awt.Toolkit
import java.awt.datatransfer.StringSelection
import java.util.*
import java.util.stream.Collectors


/**
 * 动态插入sqlaction
 * @author liudo
 * @date 2023/12/14
 * @constructor 创建[DynamicInsertSQLAction]
 */
class DynamicInsertSQLAction : AnAction() {
    override fun actionPerformed(event: AnActionEvent) {
        val editor = event.getRequiredData(CommonDataKeys.EDITOR)
        // 获取选中的文本
        val selectedText = editor.selectionModel.selectedText
        if (!selectedText.isNullOrEmpty()) {
            // 打印选中的文本内容
            val fields = selectedText.replace(Regex("\\s+"), "")
                .split(",".toRegex())
                .dropLastWhile { it.isEmpty() }
                .toTypedArray()
            val generateInsert = generateInsert(fields)
            val clipboard = Toolkit.getDefaultToolkit().systemClipboard
            val stringSelection = StringSelection(generateInsert)
            clipboard.setContents(stringSelection, null)
            CopySuccessNotification.showCopySuccessNotification(editor.project)
        } else {
            Messages.showInfoMessage(editor.project, "You did not select text!", "提示");
        }

    }
}

/**
 * 生成新增
 * @param [sql] sql
 * @return [String]
 */
private fun generateInsert(fields: Array<String>): String {
    return Arrays.stream(fields).map { field: String ->
        var field = field
        if (field.contains("_")) {
            val split = field.split("_".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
            field = Arrays.stream(split)
                .map { item: String -> item.substring(0, 1).uppercase(Locale.getDefault()) + item.substring(1) }
                .collect(Collectors.joining())
            field = field.substring(0, 1).lowercase(Locale.getDefault()) + field.substring(1)
        }
        String.format("#{%s}", field)
    }.collect(Collectors.joining(","))
}
